package com.shuorikeji.huohuo.ui.dj;

import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bytedance.sdk.djx.model.DJXDrama;
import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdLoadType;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAdSdk;
import com.bytedance.sdk.openadsdk.TTRewardVideoAd;
import com.bytedance.sdk.openadsdk.mediation.ad.MediationAdSlot;
import com.google.android.material.imageview.ShapeableImageView;
import com.shuorikeji.huohuo.R;
import com.shuorikeji.huohuo.adapter.CsjDjAdapter;
import com.shuorikeji.huohuo.adapter.DjJsAdapter;
import com.shuorikeji.huohuo.adapter.DjVideoAdapter;
import com.shuorikeji.huohuo.base.BasePresenterActivity;
import com.shuorikeji.huohuo.bean.DjDetailMainBean;
import com.shuorikeji.huohuo.bean.DjDetailSubBean;
import com.shuorikeji.huohuo.bean.DjDetailVideoBean;
import com.shuorikeji.huohuo.bean.DjInfoBean;
import com.shuorikeji.huohuo.callback.ClickCallBack;
import com.shuorikeji.huohuo.common.Constant;
import com.shuorikeji.huohuo.mvp.AllPresenter;
import com.shuorikeji.huohuo.utils.BusinessUtils;
import com.shuorikeji.huohuo.utils.CustomStatusBarUtil;
import com.shuorikeji.huohuo.utils.GsonUtil;
import com.shuorikeji.huohuo.utils.ToastShowUtil;
import com.shuorikeji.huohuo.view.GridDividerItemDecoration;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import cn.jzvd.JZUtils;
import cn.jzvd.Jzvd;
import cn.jzvd.JzvdStd;

public class DjDetailActivity extends BasePresenterActivity<AllPresenter> {
    @BindView(R.id.rv_data)
    RecyclerView rvData;
    @BindView(R.id.iv_dz)
    ImageView ivDz;
    @BindView(R.id.tv_dzs)
    TextView tvDzs;
    @BindView(R.id.iv_sc)
    ImageView ivSc;
    @BindView(R.id.ll_xj)
    LinearLayout llZj;
    @BindView(R.id.ll_top_bg)
    LinearLayout llTopBg;
    @BindView(R.id.siv_fm)
    ShapeableImageView sivFm;
    @BindView(R.id.tv_dj_name)
    TextView tvDjName;
    @BindView(R.id.tv_dj_tag)
    TextView tvDjTag;
    @BindView(R.id.tv_add_zj)
    TextView tvAddZj;
    @BindView(R.id.tv_jq_jj_tab)
    TextView tvJqJjTab;
    @BindView(R.id.tv_jj_tab)
    TextView tvJjTab;
    @BindView(R.id.ll_jq_jj_ui)
    LinearLayout llJqJjUI;
    @BindView(R.id.tv_jj)
    TextView tvJqJj;
    @BindView(R.id.rv_same_dj)
    RecyclerView rvSameDj;
    @BindView(R.id.ll_jj_ui)
    LinearLayout llJjUI;
    @BindView(R.id.rv_jj)
    RecyclerView rvJj;

    private int DJ_ID;
    private List<DjDetailVideoBean> djVideoList = new ArrayList<>();
    private DjVideoAdapter djVideoAdapter;
    private DjDetailSubBean djInfo;
    private int curDjIndex;
    private long curPlayJd;
    private String ALL_DJ;
    private List<DJXDrama> djList = new ArrayList<>();
    private CsjDjAdapter djAdapter;
    private DjJsAdapter djJsAdapter;
    private int lastVisibleDjItem;
    private long seeJdTemp;//浏览进度占位
    private String CSJ_INFO;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getmImmersionBar().reset().statusBarColor(R.color.transparent).statusBarDarkFont(true, 0.2f).init();
        CustomStatusBarUtil.with(DjDetailActivity.this).init();
    }

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_dj_detail);
    }

    @Override
    protected void initData() {
        seeJdTemp = 0;
        curDjIndex = 0;
        initAdapter();
        initIntent();
        initClick();
    }

    private void initAdapter() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(DjDetailActivity.this, LinearLayoutManager.VERTICAL, false);
        rvData.setLayoutManager(linearLayoutManager);
        djVideoAdapter = new DjVideoAdapter(DjDetailActivity.this, new ClickCallBack() {
            @Override
            public void onClick(int flag, Object object) {
                switch (flag) {
                    case 1:
                        DjDetailVideoBean data = (DjDetailVideoBean) object;
                        break;
                    case 2:
                        finish();
                        break;
                    case 3:
                        //喜欢剧集
                        DjDetailVideoBean data1 = (DjDetailVideoBean) object;
                        dzOrQxJj(data1.getId());
                        break;
                    case 5:
                        //选集
                        llZj.setVisibility(View.VISIBLE);
                        llZj.startAnimation(AnimationUtils.loadAnimation(DjDetailActivity.this, R.anim.dialog_bottom_in_anim));
                        setXjTab(1);
                        djJsAdapter.setData(djVideoList);
                        break;
                    case 6:
                        //当前播放进度（秒）
                        curPlayJd = (long) object;
                        if (djVideoList != null && djVideoList.size() > 0) {
                            if (curDjIndex < djVideoList.size()) {
                                if (curPlayJd != seeJdTemp) {
                                    seeJdTemp = curPlayJd;
                                    djSeeJl(djVideoList.get(curDjIndex).getId());
                                }
                            }
                        }
                        break;
                    case 7:
                        DjDetailVideoBean data2 = (DjDetailVideoBean) object;
                        csjAd(data2);
                        break;
                }
            }
        });
        rvData.setAdapter(djVideoAdapter);
        PagerSnapHelper snapHelper = new PagerSnapHelper();
        snapHelper.attachToRecyclerView(rvData);
        rvData.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                switch (newState) {
                    case RecyclerView.SCROLL_STATE_IDLE:
                        //停止滚动
                        /**在这里执行，视频的自动播放与停止*/
                        autoPlayVideo(recyclerView);
                        break;
                    case RecyclerView.SCROLL_STATE_DRAGGING:
                        //拖动
                        autoPlayVideo(recyclerView);
                        break;
                    case RecyclerView.SCROLL_STATE_SETTLING:
                        //惯性滑动
                        JzvdStd.releaseAllVideos();
                        break;
                }
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                // 获取第一个完全可见的item位置
                curDjIndex = ((LinearLayoutManager) recyclerView.getLayoutManager()).findFirstVisibleItemPosition();
                lastVisibleDjItem = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastVisibleItemPosition();
                if (djVideoList != null && djVideoList.size() > 0) {
                    if (curDjIndex < djVideoList.size()) {
                        for (int i = 0; i < djVideoList.size(); i++) {
                            if (i == curDjIndex) {
                                djVideoList.get(i).setPlaying(true);
                            } else {
                                djVideoList.get(i).setPlaying(false);
                            }
                        }
                    }
                }
                setDzSc();
            }
        });

        rvSameDj.setLayoutManager(new GridLayoutManager(this, 3, GridLayoutManager.VERTICAL, false));
        rvSameDj.addItemDecoration(new GridDividerItemDecoration(60));
        djAdapter = new CsjDjAdapter(DjDetailActivity.this, new ClickCallBack() {
            @Override
            public void onClick(int flag, Object object) {
                switch (flag) {
                    case 1:
                        DjInfoBean data = (DjInfoBean) object;
                        DJ_ID = data.getId();
                        getDjDetail();
                        break;
                }
            }
        });
        rvSameDj.setAdapter(djAdapter);

        rvJj.setLayoutManager(new GridLayoutManager(this, 6, GridLayoutManager.VERTICAL, false));
        rvJj.addItemDecoration(new GridDividerItemDecoration(40));
        djJsAdapter = new DjJsAdapter(DjDetailActivity.this, new ClickCallBack() {
            @Override
            public void onClick(int flag, Object object) {
                switch (flag) {
                    case 1:
                        DjDetailVideoBean data = (DjDetailVideoBean) object;
                        for (int i = 0; i < djVideoList.size(); i++) {
                            if (data.getId() == djVideoList.get(i).getId()) {
                                rvData.smoothScrollToPosition(i);
                                djVideoList.get(i).setPlaying(true);
                            } else {
                                djVideoList.get(i).setPlaying(false);
                            }
                        }
                        djJsAdapter.setData(djVideoList);
                        break;
                }
            }
        });
        rvJj.setAdapter(djJsAdapter);
    }

    /**
     * 自动播放
     */
    private void autoPlayVideo(RecyclerView recyclerView) {
        if (curDjIndex == 0 && lastVisibleDjItem == 0 && recyclerView.getChildAt(0) != null) {
            JzvdStd videoView = null;
            if (recyclerView != null && recyclerView.getChildAt(0) != null) {
                videoView = recyclerView.getChildAt(0).findViewById(R.id.jz_video);
            }
            if (videoView != null) {
                if (videoView.state == JzvdStd.STATE_NORMAL || videoView.state == JzvdStd.STATE_PAUSE) {
                    Jzvd.setVideoImageDisplayType(Jzvd.VIDEO_IMAGE_DISPLAY_TYPE_FILL_SCROP);
                    JZUtils.clearSavedProgress(DjDetailActivity.this, "");
                    videoView.startVideo();
                }
            }
        }
        for (int i = 0; i <= lastVisibleDjItem; i++) {
            if (recyclerView == null || recyclerView.getChildAt(i) == null) {
                return;
            }
            JzvdStd videoView = recyclerView.getChildAt(i).findViewById(R.id.jz_video);
            if (videoView != null) {
                Rect rect = new Rect();
                //获取视图本身的可见坐标，把值传入到rect对象中
                videoView.getLocalVisibleRect(rect);
                //获取视频的高度
                int videoHeight = videoView.getHeight();
                if (rect.top <= 100 && rect.bottom >= videoHeight) {
                    if (videoView.state == JzvdStd.STATE_NORMAL || videoView.state == JzvdStd.STATE_PAUSE) {
                        videoView.startVideo();
                    }
                    return;
                }
                JzvdStd.releaseAllVideos();
            } else {
                JzvdStd.releaseAllVideos();
            }
        }
    }

    private void initIntent() {
        Intent intent = getIntent();
        DJ_ID = intent.getIntExtra("DJ_ID", -1);
        ALL_DJ = intent.getStringExtra("ALL_DJ");
        CSJ_INFO = intent.getStringExtra("CSJ_INFO");
        try {
            djList = GsonUtil.fromJsonArray(ALL_DJ, DJXDrama.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        getDjDetail();
    }

    /**
     * @param flag 1剧情简介
     *             2剧集
     */
    private void setXjTab(int flag) {
        tvJqJjTab.setTextColor((flag == 1) ? getResources().getColor(R.color.color_191919) : getResources().getColor(R.color.color_999999));
        BusinessUtils.setTxtFold(tvJqJjTab, (flag == 1));
        llJqJjUI.setVisibility((flag == 1) ? View.VISIBLE : View.GONE);

        tvJjTab.setTextColor((flag == 2) ? getResources().getColor(R.color.color_191919) : getResources().getColor(R.color.color_999999));
        BusinessUtils.setTxtFold(tvJjTab, (flag == 2));
        llJjUI.setVisibility((flag == 2) ? View.VISIBLE : View.GONE);
    }

    private void getDjDetail() {
        mPresenter.djDetail(true, DJ_ID, 2, CSJ_INFO, new ClickCallBack() {
            @Override
            public void onClick(int flag, Object object) {
                switch (flag) {
                    case 1:
                        DjDetailMainBean data = (DjDetailMainBean) object;
                        djInfo = data.getData();
                        djVideoList.clear();
                        djVideoList.addAll(data.getData().getVideo_data());
                        if (djVideoList != null && djVideoList.size() > 0) {
                            djVideoList.get(0).setPlaying(true);
                        }
                        djVideoAdapter.setData(djVideoList, data.getData().getName(), data.getData().getNums());
                        showDjInfo();
                        break;
                    case 2:
                        String msg = (String) object;
                        ToastShowUtil.showToastCenter(DjDetailActivity.this, msg);
                        break;
                }
            }
        });
    }

    private void showDjInfo() {
        if (djInfo != null) {
            BusinessUtils.setLoadImg(DjDetailActivity.this, Constant.IMG_OSS_BASE_URL + djInfo.getImg(), sivFm);
            tvDjName.setText(djInfo.getName());
            tvDjTag.setText(djInfo.getType());
            tvAddZj.setText((djInfo.getFollow_status() == 2) ? "加入追剧" : "已追");
            tvAddZj.setTextColor((djInfo.getFollow_status() == 2) ? getResources().getColor(R.color.color_191919) :
                    getResources().getColor(R.color.color_999999));
            tvAddZj.setBackground((djInfo.getFollow_status() == 2) ? getResources().getDrawable(R.drawable.shape_13_f9e141) :
                    getResources().getDrawable(R.drawable.shape_13_f2f2f2));
            tvJqJj.setText(djInfo.getText());
            djAdapter.setData(djList);
        }
    }

    /**
     * 设置点赞收藏
     */
    private void setDzSc() {
        if (djVideoList != null && djVideoList.size() > 0) {
            if (curDjIndex < djVideoList.size()) {
                tvDzs.setText(String.valueOf(djVideoList.get(curDjIndex).getGive()));
                ivDz.setImageResource((djVideoList.get(curDjIndex).getLove_status() == 1) ? R.mipmap.icon_dj_detail_ydz : R.mipmap.icon_dj_detail_dz);
                ivSc.setImageResource((djVideoList.get(curDjIndex).getFollow_status() == 1) ? R.mipmap.icon_dj_detail_ysc : R.mipmap.icon_dj_detail_sc);
            }
        }
    }

    /**
     * 添加/取消点赞短剧剧集
     *
     * @param id 剧集id
     */
    private void dzOrQxJj(int id) {
        mPresenter.djDz(true, DJ_ID, id, new ClickCallBack() {
            @Override
            public void onClick(int flag, Object object) {
                switch (flag) {
                    case 1:
                        if (djVideoList.get(curDjIndex).getLove_status() == 1) {
                            djVideoList.get(curDjIndex).setLove_status(2);
                            djVideoList.get(curDjIndex).setGive(djVideoList.get(curDjIndex).getGive() - 1);
                            setDzSc();
                        } else {
                            djVideoList.get(curDjIndex).setLove_status(1);
                            djVideoList.get(curDjIndex).setGive(djVideoList.get(curDjIndex).getGive() + 1);
                            setDzSc();
                        }
                        break;
                    case 2:
                        String msg = (String) object;
                        ToastShowUtil.showToastCenter(DjDetailActivity.this, msg);
                        break;
                }
            }
        });
    }

    /**
     * 追剧
     *
     * @param id 剧集id
     */
    private void addDeleteZj(int id) {
        mPresenter.addDeleteZj(true, DJ_ID, id, curPlayJd, new ClickCallBack() {
            @Override
            public void onClick(int flag, Object object) {
                switch (flag) {
                    case 1:
                        if (djVideoList != null && djVideoList.size() > 0) {
                            if (curDjIndex < djVideoList.size()) {
                                if (djVideoList.get(curDjIndex).getFollow_status() == 1) {
                                    djVideoList.get(curDjIndex).setFollow_status(2);
                                } else {
                                    djVideoList.get(curDjIndex).setFollow_status(1);
                                }
                                setDzSc();
                            }
                        }
                        break;
                    case 2:
                        String msg = (String) object;
                        ToastShowUtil.showToastCenter(DjDetailActivity.this, msg);
                        break;
                }
            }
        });
    }

    private void djSeeJl(int jjId) {
        mPresenter.djSeeJl(false, DJ_ID, jjId, curPlayJd, new ClickCallBack() {
            @Override
            public void onClick(int flag, Object object) {
                switch (flag) {
                    case 1:

                        break;
                    case 2:
                        String msg = (String) object;
                        ToastShowUtil.showToastCenter(DjDetailActivity.this, msg);
                        break;
                }
            }
        });

    }

    private void csjAd(DjDetailVideoBean data) {
        TTAdNative adNativeLoader = TTAdSdk.getAdManager().createAdNative(this);//需要传activity，切记！！！
        AdSlot adslot = new AdSlot.Builder()
                .setCodeId(Constant.CSJ_AD_ID)
                .setOrientation(TTAdConstant.VERTICAL)//横竖屏设置
                .setAdLoadType(TTAdLoadType.PRELOAD)
                .setMediationAdSlot(new MediationAdSlot
                        .Builder()
                        .build())
                .build();
        adNativeLoader.loadRewardVideoAd(adslot, new TTAdNative.RewardVideoAdListener() {
            @Override
            public void onError(int i, String s) {
                ToastShowUtil.showToastCenter(DjDetailActivity.this, "穿山甲广告错误：" + i + "===" + s);
            }

            @Override
            public void onRewardVideoAdLoad(TTRewardVideoAd ttRewardVideoAd) {

            }

            @Override
            public void onRewardVideoCached() {

            }

            @Override
            public void onRewardVideoCached(TTRewardVideoAd ttRewardVideoAd) {
                //可在该回调后进行广告展示
                ttRewardVideoAd.setRewardAdInteractionListener(new TTRewardVideoAd.RewardAdInteractionListener() {
                    @Override
                    public void onAdShow() {

                    }

                    @Override
                    public void onAdVideoBarClick() {

                    }

                    @Override
                    public void onAdClose() {

                    }

                    @Override
                    public void onVideoComplete() {

                    }

                    @Override
                    public void onVideoError() {

                    }

                    @Override
                    public void onRewardVerify(boolean b, int i, String s, int i1, String s1) {

                    }

                    @Override
                    public void onRewardArrived(boolean isRewardValid, int rewardType, Bundle extraInfo) {
                        if (!isRewardValid) {
                            Log.d("wxl", "穿山甲广告发送奖励失败");
                            return;
                        } else {
                            djAdJsDj(data);
                        }
                    }

                    @Override
                    public void onSkippedVideo() {

                    }
                });
                ttRewardVideoAd.showRewardVideoAd(DjDetailActivity.this);
            }
        });
    }

    private void djAdJsDj(DjDetailVideoBean data) {
        mPresenter.djAdJsDj(true, 1, data.getId(), data.getWeigh(), 2, new ClickCallBack() {
            @Override
            public void onClick(int flag, Object object) {
                switch (flag) {
                    case 1:
                        getDjDetail();
                        break;
                    case 2:
                        String msg = (String) object;
                        ToastShowUtil.showToastCenter(DjDetailActivity.this, msg);
                        break;
                }
            }
        });
    }

    private void initClick() {
        ivDz.setOnClickListener(view -> {
            if (djVideoList != null && djVideoList.size() > 0) {
                if (curDjIndex < djVideoList.size()) {
                    dzOrQxJj(djVideoList.get(curDjIndex).getId());
                }
            }
        });
        ivSc.setOnClickListener(view -> {
            if (djVideoList != null && djVideoList.size() > 0) {
                if (curDjIndex < djVideoList.size()) {
                    addDeleteZj(djVideoList.get(curDjIndex).getId());
                }
            }
        });
        llTopBg.setOnClickListener(view -> {
            llZj.setVisibility(View.GONE);
            llZj.startAnimation(AnimationUtils.loadAnimation(DjDetailActivity.this, R.anim.dialog_bottom_out_anim));
        });
        tvJqJjTab.setOnClickListener(view -> {
            setXjTab(1);
        });
        tvJjTab.setOnClickListener(view -> {
            setXjTab(2);
        });
    }

    @Override
    public void onBackPressed() {
        if (Jzvd.backPress()) {
            return; // 处理全屏播放时的返回键
        }
        super.onBackPressed();
    }

    @Override
    protected void onPause() {
        super.onPause();
        Jzvd.releaseAllVideos();
    }
}